package com.srpingde.hhh;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.springde.hhh.R;
import com.srpingde.hhh.application.HhhApp;
import com.srpingde.hhh.http.AsyncHttpResponseHandler;
import com.srpingde.hhh.jiekou.HHHIml;
import com.srpingde.hhh.jiekou.HHHInterface;

public class HHHMeiTuXiangQing extends Activity{
	ImageView show_bigimage;
	RelativeLayout bigimage_rl;
	//WeiQuTianDiMeiTuBean bean;
	//WeiQuFenLeiBean fenLeiBean;
	ImageView show_iv;
	Bitmap bigBitmap;
	HHHIml weiQuIml;
	String image,pid;
	ImageView back;
	String name ;
	Boolean hideShoucang;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wi_qu_fen_lei_xiang_qing);
		show_bigimage = (ImageView) findViewById(R.id.show_bigimage);
		bigimage_rl = (RelativeLayout) findViewById(R.id.bigimage_rl);
		show_iv = (ImageView) findViewById(R.id.show_iv);
		weiQuIml = new HHHIml();
		back = (ImageView) findViewById(R.id.back);
		image = getIntent().getStringExtra("image");
		pid = getIntent().getStringExtra("id");
		name = getIntent().getStringExtra("name");
    	hideShoucang = getIntent().getBooleanExtra("hideShoucang", false);
    	if( hideShoucang == true ){
    		 ((Button)findViewById(R.id.collection)).setVisibility(View.GONE);
    	}
    	

		final ImageView kvShow = show_iv;
		ImageLoader.getInstance().loadImage(HHHIml.httpHeader+image, new SimpleImageLoadingListener(){
			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap bitmap) {
				kvShow.setImageBitmap(bitmap);
				bigBitmap = bitmap;
			}
		});
		layout();
    
	}
	private void bigImageViewGone(){
    	bigimage_rl.setVisibility(View.GONE);
    }

	//收藏
    private void collection(){
    	String url = HHHInterface.httpHeader + "api.php?tab=favorite&act=add&pid="+pid+"&uid="+HhhApp.getInstance().getUid()+"&type=2";
    	Log.e("mytag", url+"================收藏返回的数据");
    	weiQuIml.loginHttp(HHHMeiTuXiangQing.this,url, 
    			new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				Log.e("mytag", content+"================收藏返回的数据");
				try {
					JSONObject jsonObject = new JSONObject(content);
					if(jsonObject.getBoolean("return")){
						HhhApp.getInstance().showDialog(HHHMeiTuXiangQing.this, "收藏成功");
					}else if(!jsonObject.getBoolean("return")){
						HhhApp.getInstance().showDialog(HHHMeiTuXiangQing.this, "已经收藏过了");
					}else{
						HhhApp.getInstance().showDialog(HHHMeiTuXiangQing.this, "收藏失败");
					}
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});	
    }
	public void onClick(View v){
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;

		case R.id.show_iv:
			if(bigBitmap != null){
				bigimage_rl.setVisibility(View.VISIBLE);
				show_bigimage.setImageBitmap(bigBitmap);
				show_bigimage.setOnTouchListener(new MulitPointTouchListener());
			}
			break;
		case R.id.collection:
			if(!HhhApp.getInstance().getUname().equals("")){
				collection();
			}else{
				HhhApp.getInstance().showDialog(HHHMeiTuXiangQing.this, "请先登录");
			}
			break;
		}
	}
	class MulitPointTouchListener implements OnTouchListener {
		Matrix matrix = new Matrix();
		Matrix savedMatrix = new Matrix();
		Matrix defaultMatrix;

		float X1;
		float Y1;
		float X2;
		float Y2;

		static final int NONE = 0;
		static final int DRAG = 1;
		static final int ZOOM = 2;
		int mode = NONE;

		PointF start = new PointF();
		PointF mid = new PointF();
		float dragX = 0;
		float dragY = 0;
		float oldDist = 1f;
		// ,defaultDist = 1f
		// float totalScale = 1f;
		boolean isDragableX = false;
		boolean isDragableY = false;
		boolean ischeck = false;

		// Rect rect = new Rect();
		float[] dValues = new float[9];
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			ImageView view = (ImageView) v;
			// view.setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS);
			float newDist = 0f;
			float[] values = new float[9];
			// view.getDrawable().getBounds().
			switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				X1 = event.getX();
				Y1 = event.getY();
				if (null == defaultMatrix) {
					defaultMatrix = view.getImageMatrix();
					defaultMatrix.getValues(dValues);
					// rect = view.getDrawable().getBounds();
					// defaultMatrix.getValues(dValues);
				}
				view.setScaleType(ScaleType.MATRIX);
				matrix.set(view.getImageMatrix());
				savedMatrix.set(matrix);
				start.set(event.getX(), event.getY());
				if (isDragableX || isDragableY)
					mode = DRAG;
				else
					mode = NONE;
				break;
			case MotionEvent.ACTION_POINTER_DOWN:
				oldDist = spacing(event);
				if (oldDist > 10f) {
					savedMatrix.set(matrix);
					midPoint(mid, v);
					mode = ZOOM;
				}
				break;
			case MotionEvent.ACTION_UP:
				
			case MotionEvent.ACTION_POINTER_UP:
				try{
				/*
				 * Matrix mMoveMatrix = view.getImageMatrix();
				 * mMoveMatrix.getValues(values); //获取图片描述的具体值：9个长度的int类型数组 Rect
				 * rect = view.getDrawable().getBounds(); float left =
				 * values[2]; float right = left + rect.width() * values[0];
				 * //其实就是下面的width+left float width = rect.width() * values[0];
				 * float height = rect.height() * values[0];
				 */
				X2 = event.getX();

				Y2 = event.getY();
				if (Math.abs(X1 - X2) < 6) {
					bigImageViewGone();
					return false; // distance is smaller, as the click event
				}
				if (Math.abs(X1 - X2) > 60) {// onTouch real events
					if (mode == DRAG) {
						getValues(view, values);
						// matrix.getValues(values);
						Rect rect = view.getDrawable().getBounds();
						float left = values[2];
						float right = left + rect.width() * values[0]; // 其实就是下面的width+left
						float top = values[5];
						float bottom = top + rect.height() * values[0];
						if (isDragableX) {
							if (left > 0) {
								dragX = -left;
							} else if (right < view.getWidth()) {
								dragX = view.getWidth() - right;
							} else {
								dragX = 0;
							}
						}
						if (isDragableY) {
							if (top > 0) {
								dragY = -top;
							} else if (bottom < view.getHeight()) {
								dragY = view.getHeight() - bottom;
							} else {
								dragY = 0;
							}
						}
						matrix.postTranslate(dragX, dragY);
					}
					mode = NONE;
					// Rect curr = view.getDrawable().getBounds();
					getValues(view, values);
					/*
					 * String curr = ""; for(float n : currWidth){ curr +=
					 * n+"\t"; }
					 */
					Log.d("width", "currwidth:" + values[0] + "  dWidth:"
							+ dValues[0]);
					if (values[0] <= dValues[0]) {
						// Log.d("size", "defaultSize:"+
						view.setScaleType(ScaleType.CENTER_INSIDE);
						matrix.set(defaultMatrix);
						isDragableX = false;
						isDragableY = false;
						// matrix.set(defaultMatrix);
						// matrix.preScale(1, 1, mid.x, mid.y);
						// totalScale = 1;
					} else {
						Rect rect = view.getDrawable().getBounds();
						float left = values[2];
						float right = left + rect.width() * values[0]; // 其实就是下面的width+left
						float top = values[5];
						float bottom = top + rect.height() * values[0];
						isDragableX = left < 0 || right > view.getWidth();
						isDragableY = top < 0 || bottom > view.getHeight();

					}
				}
				}catch (Exception e) {
					// TODO: handle exception
					System.out.println(e.getMessage());
				}
				// matrix.reset();
				break;
			case MotionEvent.ACTION_MOVE:
				if (mode == DRAG) {

					matrix.set(savedMatrix);
					getValues(view, values);
					// matrix.getValues(values);
					Rect rect = view.getDrawable().getBounds();
					float left = values[2];
					float right = left + rect.width() * values[0]; // 其实就是下面的width+left
					float top = values[5];
					float bottom = top + rect.height() * values[0];
					// float width = rect.width() * values[0];
					// float height = rect.height() * values[0];
					if (isDragableX)
						dragX = (event.getX() - start.x);
					else
						dragX = 0;
					if (isDragableY)
						dragY = (event.getY() - start.y);
					else
						dragY = 0;
					matrix.postTranslate(dragX, dragY);
				} else if (mode == ZOOM) {
					try{
						newDist = spacing(event);
						if (newDist > 10f) {
							matrix.set(savedMatrix);
							float scale = newDist / oldDist;
							// scale = 0.8f;
							// totalScale = totalScale*scale;
							matrix.postScale(scale, scale, mid.x, mid.y);
							// Log.d("scale--------------", totalScale+"");
						}
					}catch (Exception e) {
						// TODO: handle exception
						System.out.println(e.getMessage());
					}
				}
				break;
			}

			view.setImageMatrix(matrix);
			return true;
		}

		private void getValues(ImageView view, float[] values) {
			Matrix mMoveMatrix = view.getImageMatrix();
			mMoveMatrix.getValues(values);
			// Rect rect = view.getDrawable().getBounds();
		}

		private float spacing(MotionEvent event) {
			float x = event.getX(0) - event.getX(1);
			float y = event.getY(0) - event.getY(1);
			return (float) Math.sqrt(x * x + y * y);
		}

		private void midPoint(PointF point, MotionEvent event) {
			float x = event.getX(0) + event.getX(1);
			float y = event.getY(0) + event.getY(1);
			point.set(x / 2, y / 2);
		}

		private void midPoint(PointF point, View v) {
			float x = v.getRight() - v.getLeft();
			float y = v.getBottom() - v.getTop();
			point.set(x / 2, y / 2);
		}
	}
	private void layout() {
		// 头的高度
		TextView top_title_tv = (TextView) findViewById(R.id.top_title);
		RelativeLayout.LayoutParams titleLayoutParams = (android.widget.RelativeLayout.LayoutParams) top_title_tv.getLayoutParams();
		titleLayoutParams.height = HhhApp.getInstance().title_h();
		top_title_tv.setLayoutParams(titleLayoutParams);
		top_title_tv.setText(name);
		
		RelativeLayout.LayoutParams backLayoutParams = (android.widget.RelativeLayout.LayoutParams) back.getLayoutParams();
		backLayoutParams.height = HhhApp.getInstance().title_h();
		back.setLayoutParams(backLayoutParams);
	}
}
